package com.raychi.demo.servlet.orders;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.raychi.demo.util.JdbcUtil;

public class OrderSaveServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.getRequestDispatcher("/product/inputOrders.jsp").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try{
			req.setCharacterEncoding("utf-8");
			String name = req.getParameter("name");
			int totalprice =Integer.valueOf(req.getParameter("totalprice"));
			saveOrders2DB(name, totalprice);
			resp.sendRedirect(req.getContextPath()+"/orders/");
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	private void saveOrders2DB(String name, int totalprice)
			throws SQLException, ClassNotFoundException {
		Connection conn = JdbcUtil.getConnection();
		String sql = "insert into orders (name,totalprice) values (?,?)";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, name);
		ps.setInt(2, totalprice);
		ps.execute();
		conn.commit();
	}
	
}
